package com.jas.common;
//@author A0098803W
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TreeMap;

import com.jas.logic.LogicAPI;
import com.jas.storage.StorageAPI;
import com.jas.storage.StorageException;

//@author A0098803W
/**
 * This class starts the thread that handles sending out notifications for
 * events stored in the notification list.
 * 
 */
public class JasTimer implements Runnable {
	private Calendar cal;
	private Calendar userCalendar;
	private TreeMap<String, Event> eventIdToEventMapping;
	private ArrayList<Event> listOfEvents;
	private ArrayList<Notification> notificationList;

	public JasTimer() {
	}

	@Override
	public void run() {

		eventIdToEventMapping = new TreeMap<String, Event>();
		listOfEvents = new ArrayList<Event>();
		notificationList = new ArrayList<Notification>();
		ArrayList<Notification> updatedNotificationList = new ArrayList<Notification>();
		boolean isMessageSent = false;

		while (true) {
			eventIdToEventMapping.clear();
			listOfEvents.clear();
			notificationList.clear();
			updatedNotificationList.clear();
			
			try {
				Thread.sleep(30000);

				notificationList = (ArrayList<Notification>) StorageAPI
						.loadNotificationList();
				for (Notification notification : notificationList) {
					cal = Calendar.getInstance();
					int currentDay = cal.get(Calendar.DAY_OF_MONTH);
					int currentMonth = cal.get(Calendar.MONTH);
					int currentYear = cal.get(Calendar.YEAR);
					int currentHour = cal.get(Calendar.HOUR);
					int currentMinute = cal.get(Calendar.MINUTE);
					userCalendar = notification.getTimeToNotify();
					int userCurrentDay = userCalendar
							.get(Calendar.DAY_OF_MONTH);
					int userCurrentMonth = userCalendar.get(Calendar.MONTH);
					int userCurrentYear = userCalendar.get(Calendar.YEAR);
					int userCurrentHour = userCalendar.get(Calendar.HOUR);
					int userCurrentMinute = userCalendar.get(Calendar.MINUTE);
					
					if (currentDay == userCurrentDay
							&& currentMonth == userCurrentMonth
							&& currentYear == userCurrentYear
							&& currentHour == userCurrentHour
							&& currentMinute == userCurrentMinute
							&& !notification.isExecutionStatus()) {
						isMessageSent = new MessageGateway()
								.sendMessage(notification);
						if (isMessageSent) {
							notification.setExecutionStatus(true);
							continue;
						}
					}
					else if(cal.after(userCalendar)){
						notification.setExecutionStatus(true);
						
						continue;
					}
					updatedNotificationList.add(notification);

				}
				StorageAPI.storeNotificationList(updatedNotificationList);

			} catch (InterruptedException | StorageException e) {

			}

		}
	}
}